<?php
/**
 * 数据库模型类
*/

namespace houze;

class Model {
    /**
     * 大写字母
    */
    private $_word = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    /**
     * 表名
    */
    protected $table;
    /**
     * 当前模型名称
    */ 
    protected $name;
    /**
     * Db实例
    */
    protected $Db;

    /**
     * 初始化连接池
    */
    public function __construct($type=null) {
        // 自动创建表名
        if(!$this->table && !$this->name){
            // 获取子类名
            $array = explode('\\', static::class);
            $class = end($array);
            $lenth = strrpos($class, 'Model');
            $class = substr($class, 0, $lenth);
    
            // 为表名大写字母转_符号拼接
            foreach ($this->_word as $v) {
                $class = str_replace($v, '_'.$v, $class);
            }
            $this->name = strtolower(ltrim($class, '_'));
        }
        // 自动创建Db实例
        $this->Db = new \houze\Db($type);
    }

    /**
     * 当实例使用完成后，自动归还连接池
    */
    public function __destruct() {
		$this->Db->return();
    }
    
    /**
     * 驱动函数注入
    */
    public function __call($name, $arguments=[]) {
        if (!$this->Db) return false;
        if (empty($name)) return false;
        
        if (!$this->Db->getTable()) {
            if($this->table) $this->Db = $this->Db->table($this->table);
            if($this->name) $this->Db = $this->Db->name($this->name);
        }
        return $this->Db->$name(...$arguments);
    }
}